package com.naodong.shenluntiku.mvp.view.webView;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ClipboardUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.naodong.shenluntiku.R;
import com.naodong.shenluntiku.intergation.voice.PlayVoiceListener;
import com.naodong.shenluntiku.intergation.voice.PlayVoiceManager;
import com.naodong.shenluntiku.intergation.voice.PlayVoiceStatus;
import com.naodong.shenluntiku.mvp.model.data.manager.TokenManager;
import com.naodong.shenluntiku.util.TimeUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import me.shingohu.man.base.BaseMVPFragment;
import me.shingohu.man.di.component.AppComponent;
import me.shingohu.man.util.ToastUtil;

/**
 * Created by hujie on 17/5/12.
 */

public class TKWebViewFragment extends BaseMVPFragment {


    @BindView(R.id.bridgeWebView)
    TKWebView bridgeWebView;

    @BindView(R.id.errorPageView)
    View errorPageView;

    @BindView(R.id.pb)
    ProgressBar pb;
    private String url;
    TKWebViewListener tkWebViewListener;


    View playVoiceView;

    @BindView(R.id.playVoiceViewStub)
    ViewStub playVoiceViewStub;

    PlayVoiceManager playVoiceManager;

    public void setUrl(String url) {
        this.url = url;
    }


    public static TKWebViewFragment getInstance() {
        TKWebViewFragment fragment = new TKWebViewFragment();
        return fragment;
    }


    public void setTkWebViewListener(TKWebViewListener tkWebViewListener) {
        this.tkWebViewListener = tkWebViewListener;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {

    }

    @Override
    protected void onViewCreated(Bundle savedInstanceState) {
        initWebView();
    }

    private void initWebView() {
        bridgeWebView.setTkWebViewListener(new TKWebViewListener() {
            @Override
            public void setReceiveTitle(String title) {
                if (tkWebViewListener != null) {
                    tkWebViewListener.setReceiveTitle(title);
                }
            }

            @Override
            public void showErrorPage() {
                errorPageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished() {
                if (tkWebViewListener != null) {
                    tkWebViewListener.onPageFinished();
                }
            }

            @Override
            public void showProgress() {
                if (pb != null) {
                    pb.setVisibility(View.VISIBLE);
                }
                if (errorPageView != null) {
                    errorPageView.setVisibility(View.GONE);
                }
            }

            @Override
            public void download(String url) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                getContext().startActivity(intent);
            }

            @Override
            public void onProgressChanged(int progress) {
                if (pb != null) {
                    pb.setProgress(progress);
                    if (progress == 100) {
                        pb.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });

        registerHandler();

    }


    public void registerHandler() {
        bridgeWebView.registerHandler("playVoice", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    JSONObject jo = new JSONObject(data);
                    String voiceLink = jo.optString("voiceLink");
                    if (!TextUtils.isEmpty(voiceLink)) {
                        playVoice(voiceLink);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


        bridgeWebView.registerHandler("copyNumber", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    JSONObject jo = new JSONObject(data);
                    String number = jo.optString("number");
                    ClipboardUtils.copyText(number);
                    ToastUtil.makeToast("复制成功");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void playVoice(String voiceLink) {
        if (playVoiceView == null) {
            playVoiceView = playVoiceViewStub.inflate();
            ImageView playBtn = (ImageView) playVoiceView.findViewById(R.id.playBtn);
            SeekBar seekBar = (SeekBar) playVoiceView.findViewById(R.id.progressBar);
            TextView timeTV = (TextView) playVoiceView.findViewById(R.id.timeTV);
            playBtn.setBackgroundResource(R.drawable.ico_play_play);
            timeTV.setText("");
            seekBar.setEnabled(false);
            playBtn.setEnabled(false);
            seekBar.setProgress(0);

            playVoiceManager = new PlayVoiceManager(voiceLink, new PlayVoiceListener() {
                @Override
                public void onProgress(int current, int total) {
                    seekBar.setProgress(current);
                    timeTV.setText(TimeUtil.formatMiss1((total - current) * 1000));
                }

                @Override
                public void onPrepared() {
                    seekBar.setMax(playVoiceManager.getDuration());
                    seekBar.setEnabled(true);
                    playBtn.setEnabled(true);
                }

                @Override
                public void onError() {
                    ToastUtil.makeToast("播放出错");
                    playBtn.setBackgroundResource(R.drawable.ico_play_play);
                    seekBar.setEnabled(false);
                    playBtn.setEnabled(false);
                    seekBar.setProgress(0);
                }

                @Override
                public void onComplete() {
                    playBtn.setBackgroundResource(R.drawable.ico_play_play);
                    seekBar.setProgress(seekBar.getMax());
                    timeTV.setText("00:00");

                }

                @Override
                public void onPlayMp3StatusChange(PlayVoiceStatus status) {

                }
            });


            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    if (playVoiceManager != null) {
                        playVoiceManager.setTracking(true);
                    }
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    if (playVoiceManager != null) {
                        playVoiceManager.setTracking(false);
                        playVoiceManager.seekTo(seekBar.getProgress());
                    }
                }
            });


            playBtn.setOnClickListener(v -> {
                if (playVoiceManager != null) {
                    if (playVoiceManager.getStatus() == PlayVoiceStatus.START) {
                        pausePlayVoice();
                    } else if (playVoiceManager.getStatus() == PlayVoiceStatus.PAUSR) {
                        resumePlayVoice();
                    } else if (playVoiceManager.getStatus() == PlayVoiceStatus.LOADING) {
                        ToastUtil.makeToast("正在拼命加载...");
                    } else if (playVoiceManager.getStatus() == PlayVoiceStatus.PREPARED) {
                        playPlayVoice();
                    } else if (playVoiceManager.getStatus() == PlayVoiceStatus.COMPLETE) {
                        if (seekBar.getMax() == seekBar.getProgress()) {
                            playVoiceManager.seekTo(0);
                        } else {
                            playVoiceManager.seekTo(seekBar.getProgress());
                        }
                        resumePlayVoice();
                    }
                }

            });
        }
    }

    private void releasePlayVoice() {
        if (playVoiceManager != null) {
            playVoiceManager.release();
        }
        playVoiceManager = null;
    }

    /**
     * 暂停播放
     */
    private void pausePlayVoice() {
        if (playVoiceManager != null) {
            playVoiceManager.pause();
            playVoiceView.findViewById(R.id.playBtn).setBackgroundResource(R.drawable.ico_play_play);
        }
    }


    /**
     * 继续播放
     */
    private void resumePlayVoice() {
        if (playVoiceManager != null) {
            playVoiceManager.resume();
            playVoiceView.findViewById(R.id.playBtn).setBackgroundResource(R.drawable.ico_play_pause);
        }
    }

    /**
     * 播放
     */
    public void playPlayVoice() {
        if (playVoiceManager != null) {
            playVoiceManager.play();
            playVoiceView.findViewById(R.id.playBtn).setBackgroundResource(R.drawable.ico_play_pause);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        bridgeWebView.onResume();
        bridgeWebView.resumeTimers();
    }


    @Override
    public void onPause() {
        super.onPause();
        pausePlayVoice();
        bridgeWebView.onPause();
        bridgeWebView.pauseTimers();
    }

    @Override
    public void onDestroy() {
        if (bridgeWebView != null) {
            // clearHistory();
            bridgeWebView.stopLoading();
            ((ViewGroup) bridgeWebView.getParent()).removeView(bridgeWebView);
            bridgeWebView.removeAllViews();
            bridgeWebView.destroy();
            bridgeWebView = null;
        }
        releasePlayVoice();
        super.onDestroy();
    }

    private void clearHistory() {
        bridgeWebView.clearCache(true);
        bridgeWebView.clearHistory();
    }

    @OnClick(R.id.errorPageView)
    public void onErrorPageClick() {
        bridgeWebView.reload();
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        if (TokenManager.getInstance().getToken() != null) {
            bridgeWebView.loadUrl(url, new HashMap<String, String>() {
                {
                    put("token", TokenManager.getInstance().getToken().getAccessToken());
                }
            });
        } else {
            bridgeWebView.loadUrl(url);
        }
    }

    @Override
    protected int layoutId() {
        return R.layout.tkwebview_fragment_layout;
    }
}
